package StudySpringBoot.config;

import StudySpringBoot.pojo.User;
import StudySpringBoot.service.UserService;
import StudySpringBoot.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;

// 自定义realms，继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserServiceImpl userService;

    //  授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 进入被拦截的url，就会进这个info
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 授权应该从数据库查出权限字段
        // info.addStringPermission("user:add");
        // 从 new SimpleAuthenticationInfo(queryUser, queryUser.getPwd(), "");传递过来第一个参数user最为subject
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        // 从数据库中获取验证权限
        simpleAuthorizationInfo.addStringPermission(currentUser.getPerms());
        return simpleAuthorizationInfo;
    }

    // 用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 模拟数据库中查出用户名、密码
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User user = userService.queryUserByName(userToken.getUsername());
        // 验证用户名
        if (user == null) {
            // 用户名不正确，就抛出UnknownAccountException
            return null;
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser", user);
        // 密码验证,shiro完成，不需要用户判断.直接返回
        return new SimpleAuthenticationInfo(user, user.getPwd(), "");
    }
}
